const { query, add, update, remove, getOne, getAll } = require('../utils/dbTools')
const tableName = 'posts';

/**
 *  获取文章列表
 * @param {object} map 查询条件
*/
const getPostsList = async (map) => {
    const result = await getAll(tableName, map);
    return result
}

/**
 *  查询文章详情
 * @param {object | number} map 查询条件
*/
const getPostsInfo = async (map) => {
    if (typeof map === 'object') {
        return await getOne(tableName, map);
    }
    return await getOne(tableName, { map });
}
/**
 * 更新文章点击量 
 * @param {number} id 文章id
 * @return {boolean} 更新是否成功
 */
const postsVisitCountUpdate = async (id) => {
    if (!id) {
        return false
    }
    const result = await query(`update ${tableName} set visit_count=visit_count+1 where id=${id}`)
    // changedRows: 受影响行数
    // console.log(result.changedRows, 'result.changedRows');
    return result;
}

/**
 * 发布文章 
 * @param {object} data 文章对象
 * @return {boolean} 是否添加成功
 */
const addPosts = async (data) => {
    if (Object.keys(data).length === 0) return false
    const { insertId } = await add(data, tableName)
    // insertId: 新增的数据id
    // console.log(result.insertId, 'result.insertId');
    return insertId;
}

/**
 * 更新文章 
 * @param {object} data 文章对象
 * @return {boolean} 是否更新加成功
 */
const updatePosts = async (data) => {
    const { id } = data
    if (!id) return false
    delete data.id
    const result = await update(id, data, tableName)
    // console.log(result.changedRows, 'result.changedRows');
    return result;
}

/**
 * 删除文章 
 * @param {number} id 文章id
 * @return {boolean} 是否删除加成功
 */
const removePosts = async (id) => {
    if (!id) return false
    delete data.id
    const result = await remove(id, data, tableName)
    return result;
}

module.exports = {
    getPostsList, getPostsInfo, addPosts, updatePosts, removePosts, postsVisitCountUpdate
}